%   H(X) = Q0X0 + Q1*X1 + Q2*X2 + Q3*X3+ Q4*X4 + Q5 * X5 + Q6*X6 + Q7 *X7
% 令 X0 = 1
% 求 Q(0,1,2,3,4,5,6,7)

%样本 X Y
load('data');
Y = data(:,1);
one = ones(length(Y),1);
X = data(:,[2:8]);

%for i = 1:(length(Y))
%    pj =  mean(X(i,:));
%    max_min = max(X(i,:))- min(X(i,:));
%    for j = 1:7
%        X(i,j) = (X(i,j) - pj) / max_min;
%    endfor;
%endfor;

X = [one X];

M = size(X,1);
N = size(X,2);



%%
% get H(X)
function Hxi = HQiXi (Qi, Xi)
    Hxi = 0;
    %for i = 1:length(Xi)
    %   Hxi = Hxi + Qi(i) * Xi(i);
    %endfor;
    %更新算法
    Hxi = Qi * (Xi') ;
    %disp(Hxi);
end;

%%get sum (H(xi)-yi)*xij
function value_sum = Em (Qi, j, M, X, Y)
    value_sum = 0;
    for i = 1:M
        %get (H(x) - yi )* xij
        value_sum = value_sum + (HQiXi(Qi, X(i,:)) - Y(i)) * X(i, j);
    endfor;
end;


%%get J(Q)
function mJ = JQ (Qi,M, X, Y)
    em = 0;
    %mJ = 0;
    %get Em
    %for i = 1:M
    %    em = em + (HQiXi(Qi, X(i, :)) - Y(i)) ^ 2 ;
    %endfor;
    W = (( Qi * ( X(:,:) )' )  - Y' );
    mJ = (1/M) * sum(W.^2);
end;


%% 设置初始值
Qi = rand(1,N);
%Qi = [2 0.1 0.5 2 0.9 8 0.1 0.7 ];
ar = 0.00001;
minJ = 1;
realJq  = 0;
newQi = ones(1,N);
times = 1;

lastj = 0;

%disp(X(1,:));
%disp(Qi);
%disp(HQiXi(Qi,X(1,:)));
disp(Em(Qi,1,M,X,Y));
%disp("test");
%disp(HQiXi(Qi,X(1,:)));

%return ;

tic;
while(1)
    %tic;
    for n = 1:N
        %newQi(n) = Qi(n) - ar * (1/M) * Em (Qi, n, M, X , Y);
        W = (X(:,n))' .*  (( Qi * ( X(:,:) )' )  - Y' );
        newQi(n) = Qi(n) - ar * (1.0/M) * sum(W);
        %disp(sprintf("第 %d 次: Q(%d) = %0.2f \n", times, n, newQi(n)));
    endfor;
    %toc;
    disp(newQi);
    %set newQi
    Qi = newQi ;
    %get Jq 
    realJq = JQ(Qi, M, X, Y);
    disp(sprintf("第 %d 次: J = %0.5f \n", times, realJq));
    if realJq < minJ
        break;
    endif;
    times++;
end;
toc;
disp(Qi);

    



        



